package edu.ccut.saturn.manager.css.core;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import edu.ccut.saturn.component.DefaultComponent;
import edu.ccut.saturn.component.IParameterContext;

public class QueryMapBySQL extends DefaultComponent {
	/**
	 * 
	 */
	private static final long serialVersionUID = -7934134021328175241L;

	@Override
	public void execute(IParameterContext parameterContext) throws Exception {
		String sql = (String) parameterContext.getParameterValue(0);

		debug("QuerySQL==" + sql, parameterContext);
		if (sql != null) {
			Connection conn = null;
			Statement stat = null;
			ResultSet rs = null;
			List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();

			try {
				conn = parameterContext.getConnection();
				stat = conn.createStatement();
				rs = stat.executeQuery(sql);
				while (rs.next()) {
					int columCount = rs.getMetaData().getColumnCount();
					Map<String, Object> valueMap = new HashMap<String, Object>();
					for (int i = 1; i <= columCount; i++) {
						String columName = rs.getMetaData().getColumnName(i);
						Object value = rs.getObject(i);
						valueMap.put(columName, value);
					}
					mapList.add(valueMap);
				}
			} catch (RuntimeException e) {
				e.printStackTrace();
			} finally {
				if (rs != null) {
					rs.close();
				}
				if (stat != null) {
					stat.close();
				}
			}
			parameterContext.setParameter(1, mapList);
		}
	}
}